from random import Random

from django.core.mail import send_mail
from django.contrib.auth.hashers import make_password

from users.models import EmailVerifyRecord, UserProfile
from cjn_calendar.settings import EMAIL_FROM


def random_code(randomlength=8):
    code = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(randomlength):
        code += chars[random.randint(0, length)]
    return code


def send_register_email(email, send_type="register"):
    email_record = EmailVerifyRecord()
    if send_type == "update_email":
        code = random_code(4)
    else:
        code = random_code(16)
    email_record.code = code
    email_record.email = email
    email_record.send_type = send_type
    email_record.save()

    forget_code = random_code(6)  # 随机六位数的密码

    if send_type == "register":
        email_title = "慕学在线网注册激活链接"
        email_body = "请点击下面的链接激活你的账号: http://127.0.0.1:8000/users/active/{0}".format(code)

        send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        if send_status:
            pass
    elif send_type == "forget":
        email_title = "慕学在线网找回密码链接"
        email_body = "您的密码已被重置为{0}，请您登陆后立刻进行密码的修改。".format(forget_code)

        # 重置用户的密码
        user = UserProfile.objects.get(email=email)
        user.password = make_password(forget_code)  # 重置密码
        user.save()

        send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        if send_status:
            pass
    elif send_type == "update_email":
        email_title = "慕学在线邮箱修改验证码"
        email_body = "你的邮箱验证码为: {0}".format(code)

        send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        if send_status:
            pass
